package com.dj.mingkong.common.microservice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceContext implements ServiceConstants {
    private static final Logger log = LoggerFactory.getLogger(ServiceContext.class);
    private static final ThreadLocal<ServiceContext> LOCAL = ThreadLocal.withInitial(ServiceContext::new);
    private final Map<String, Object> mapValue = new ConcurrentHashMap();
    private MicroServiceContext microServiceContext = null;

    private ServiceContext() {
    }

    public static ServiceContext getContext() {
        return (ServiceContext) LOCAL.get();
    }

    public static void removeContext() {
        LOCAL.remove();
    }

    private MicroServiceContext getMicroServiceContext() {
        if (this.microServiceContext == null) {
            String className = "com.coli.common.microservice.SpringCloudMicroServiceContext";

            try {
                this.microServiceContext = (MicroServiceContext) Class.forName(className).newInstance();
            } catch (Exception var3) {
                log.error("{} 初始化异常", className, var3);
            }
        }

        return this.microServiceContext;
    }

    public void removeAttachmentContext() {
        if (this.microServiceContext != null) {
            this.microServiceContext.removeContext();
        }

    }

    public void set(String key, Object value) {
        if (value == null) {
            this.mapValue.remove(key);
        } else {
            this.mapValue.put(key, value);
        }

    }

    public void remove(String key) {
        this.mapValue.remove(key);
    }

    public Object get(String key) {
        return this.mapValue.get(key);
    }

    public Map<String, Object> getKeys() {
        return this.mapValue;
    }

    public void setAttachment(String key, String attachment) {
        this.set(key, attachment);
        this.getMicroServiceContext().setAttachment(key, attachment);
    }

    public void setAttachment(Map<String, String> attachmentMap) {
        this.mapValue.putAll(attachmentMap);
    }

    public String getAttachment(String key) {
        String value = (String) this.get(key);
        if (value == null) {
            value = this.getMicroServiceContext().getAttachment(key);
        }

        return value;
    }

    public void removeAttachment(String key) {
        this.remove(key);
        this.getMicroServiceContext().removeAttachment(key);
    }

    public Map<String, String> getAttachments() {
        return this.getMicroServiceContext().getAttachments();
    }
}

